<template>
  <div v-loading="loading">
    <div v-if="content.length > 0 && errors.length === 0">
      <el-button type="success" size="medium" @click="doImport">导入</el-button>
      <el-button type="danger" size="medium" @click="clearData">取消</el-button>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12">
          <div class="json_wrapper">
            <pre>{{ exerciseData }}</pre>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12">
          <div class="json_wrapper">
            <pre>{{ content }}</pre>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-else>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-alert
            v-show="errors.length > 0"
            style="margin-bottom: 12px"
            type="error"
            :closable="false"
          >
            <div slot="title">
              <i class="el-icon-error" style="margin-right: 6px"></i
              >出错了，请先检查数据内容！
            </div>
            <div style="padding-left: 15px">
              <li v-for="(msg, i) in errors" :key="'err_' + i">{{ msg }}</li>
            </div>
          </el-alert>
        </el-col>
        <div style="padding: 24px 12px">
          <el-alert type="warning" :closable="false">此功能已禁止使用</el-alert>
        </div>
        <el-form label-width="80px" disabled>
          <el-col :xs="24" :sm="12">
            <el-form-item label="练习类型" size="small">
              <el-radio-group
                v-model="exerciseData.type"
                @change="handleTypeChanged"
              >
                <el-radio :label="1">年度复训</el-radio>
                <el-radio :label="2">专项培训</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="练习名">
              <el-input
                size="small"
                v-model="exerciseData.title"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="年度">
              <el-select
                size="small"
                v-model="exerciseData.year"
                style="width: 100%"
              >
                <el-option
                  v-for="y in [
                    new Date().getFullYear(),
                    new Date().getFullYear() - 1,
                    new Date().getFullYear() - 2,
                  ]"
                  :key="'y' + y"
                  :label="y + '年'"
                  :value="y"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="计分周期">
              <el-select
                size="small"
                v-model="exerciseData.cycle"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-if="exerciseData.type == 2"
                  label="不加入复训计分"
                  :value="-1"
                >
                </el-option>
                <el-option
                  v-for="item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
                  :key="item"
                  :label="'第' + item + '轮'"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="学时">
              <el-select
                size="small"
                v-model="exerciseData.hours"
                style="width: 100%"
              >
                <el-option
                  v-for="h in [0.5, 1, 1.5, 2]"
                  :key="'h' + h"
                  :label="h + '学时'"
                  :value="h"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="科室">
              <el-select
                size="small"
                v-model="exerciseData.office"
                style="width: 100%"
              >
                <el-option
                  v-for="office in params.userAttribs.office"
                  :key="office"
                  :label="office"
                  :value="office"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="">
              <el-button
                type="primary"
                size="medium"
                icon="el-icon-paperclip"
                @click="readData"
                >解析企业微信格式</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="粘贴">
              <el-input
                size="small"
                type="textarea"
                :rows="20"
                v-model="raw"
                @change="errors = []"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>
  </div>
</template>

<script>
import { format } from "@/utils/datetime.js";
export default {
  name: "dataImportView",
  data() {
    return {
      raw: "",
      header: [],
      showInputOfExerciseData: false,
      exerciseDataBlank: "",
      exerciseData: {
        title: "终端管制室模拟机复训（练习n）",
        year: new Date().getFullYear(),
        cycle: 1,
        type: 1,
        hours: 1,
        office: "管制二室",
        description: "通过导入的数据",
        startDate: format("yyyy-MM-dd"),
        endDate: format("yyyy-MM-dd"),
        author: this.$store.getters.userName,
        updateTime: format("yyyy-MM-dd hh:mm:ss"),
        valid: 1,
        disposed: 0,
      },
      content: [],
      contentExercise: null,
      errors: [],
      warnings: [],
      loading: false,
    };
  },
  computed: {
    contentJSON() {
      return JSON.stringify(this.content, null, 2);
    },
    userList() {
      return this.$store.state.userList;
    },
    params() {
      return this.$store.state.params;
    },
    userName() {
      return this.$store.getters.userName;
    },
  },
  methods: {
    formatDate: format,
    handleTypeChanged(val) {
      if (val == 1) {
        this.exerciseData.title = "终端管制室模拟机复训（练习n）";
        if (this.exerciseData.cycle == -1) {
          this.exerciseData.cycle = 1;
        }
      } else if (val == 2) {
        this.exerciseData.title = "终端管制室模拟机专项培训（xxxx练习）";
      }
    },
    clearString(str) {
      return str
        .replace(/科目评价/g, "")
        .replace(/教员评定/g, "")
        .replace(/复训教员填写/g, "")
        .replace(/参训人员填写/g, "")
        .replace(/必填/g, "")
        .replace(/自动/g, "")
        .replace(/：/g, "")
        .replace(/（/g, "")
        .replace(/）/g, "")
        .replace(/:/g, "")
        .replace(/\(/g, "")
        .replace(/\)/g, "")
        .replace(/ /g, "");
    },
    readData() {
      this.loading = true;
      this.errors = [];
      try {
        // this.raw = this.raw.replace(/ /g, "").replace(/\/n/g, "").replace(/\/r/g, "");
        let raw = "";
        try {
          raw = this.raw
            .replace(/ /g, "")
            .replace(/\/n/g, "")
            .replace(/\/r/g, "");
        } catch (e) {
          console.log("error while replacing raw", e);
          return;
        }
        let lines = [];
        try {
          lines = raw.split("\n");
          // console.log('lines', lines);
        } catch (e) {
          console.log("error while split raw into lines", e);
          return;
        }
        let header = [];
        let content = [];
        let subjects = [];
        if (lines.length > 1) {
          try {
            header = lines[0].split("\t");
            // console.log('header', header);
          } catch (e) {
            console.log("error while split header", e);
            return;
          }
          for (let i = 0; i < header.length; i++) {
            if (header[i].indexOf("科目评价") > -1) {
              header[i] = {
                column: "subject",
                subject: this.clearString(header[i]),
              };
              subjects.push(header[i].subject);
            } else if (header[i].indexOf("教员评定（复训教员填写）") > -1) {
              header[i] = {
                column: "coachComments",
              };
            } else if (header[i].indexOf("科目自我评定") > -1) {
              header[i] = {
                column: "traineeComments",
              };
            } else if (header[i].indexOf("教员评定") > -1) {
              header[i] = {
                column: "evaluation",
                title: this.clearString(header[i]),
              };
            } else if (header[i].indexOf("训练科目评定") > -1) {
              header[i] = {
                column: "pass",
              };
            } else if (header[i].indexOf("加练意见") > -1) {
              header[i] = {
                column: "failedSubjects",
              };
            } else if (header[i].indexOf("复训时间") > -1) {
              header[i] = {
                column: "trainingDate",
              };
            } else if (header[i].indexOf("复训人员姓名") > -1) {
              header[i] = {
                column: "traineeName",
              };
            } else if (header[i].indexOf("填写人") > -1) {
              header[i] = {
                column: "coachName",
              };
            } else if (header[i].indexOf("填写时间") > -1) {
              header[i] = {
                column: "commitTime",
              };
            } else {
              header[i] = false;
            }
          }
          console.log("header", JSON.stringify(header, null, 2));
        }
        this.exerciseData.subjects = subjects;
        this.header = header;
        for (let i = 1; i < lines.length; i++) {
          let cells = lines[i].split("\t");
          // console.log('cells', JSON.stringify(cells, null, 2));
          if (cells.length != header.length) {
            console.log(
              "line length mismatch! expected",
              header.length,
              " got ",
              cells.length + ", line: " + i + ", raw: " + lines[i]
            );
            continue;
          }
          let data = {
            number: null,
            title: this.exerciseData.title,
            year: this.exerciseData.year,
            cycle: this.exerciseData.cycle,
            type: this.exerciseData.type,
            office: this.exerciseData.office,
            subjects: [],
            hours: this.exerciseData.hours,
            pass: "",
            traineeNumber: "",
            traineeName: "",
            traineeDepartment: "",
            traineeOffice: "",
            traineeGroup: "",
            traineeGrade: "",
            traineePost: "",
            traineeLicences: [],
            traineeComments: [],
            coachNumber: "",
            coachName: "",
            subjectsComments: [],
            coachComments: "",
            failedSubjects: [],
            failedSubjectsCount: 0,
            evaluations: [],
            evaluationMin: 5,
            evaluationScore: 0,
            trainingDate: "",
            history: [],
            status: 0,
            commitTime: null,
            updateTime: null,
          };
          let indexOfailedSubjects = -1;
          for (let j = 0; j < header.length; j++) {
            if (!header[j]) continue;
            if (!cells[j])
              console.log(
                "row: " +
                  (i + 1) +
                  ", col: " +
                  (j + 1) +
                  ", key: " +
                  header[j].column
              );
            if (header[j].column == "failedSubjects") {
              indexOfailedSubjects = j;
            } else if (header[j].column == "subject") {
              data.subjects.push(header[j].subject);
              data.subjectsComments.push({
                subject: header[j].subject,
                pass: "是",
                comments: cells[j].split(","),
                commentPlus: "",
              });
              if (!this.checkSubjects(header[j].subject)) {
                this.errors.push("科目名称不正确：" + header[j].subject);
              }
            } else if (header[j].column == "pass") {
              if (cells[j].indexOf("通过") > -1) {
                data.pass = "是";
              } else {
                data.pass = "否";
              }
            } else if (header[j].column == "trainingDate") {
              data.trainingDate = cells[j]
                .replace(/年/g, "-")
                .replace(/月/g, "-")
                .replace(/日/g, "");
            } else if (header[j].column == "traineeName") {
              data.traineeName = cells[j];
              data.traineeNumber = this.getUsrNum(cells[j]);
              if (data.traineeNumber === 0) {
                this.errors.push(
                  "user not found: " + cells[j] + ", row: " + (i + 1)
                );
              }
            } else if (header[j].column == "coachName") {
              data.coachName = cells[j];
              data.coachNumber = this.getUsrNum(cells[j]);
            } else if (header[j].column == "evaluation") {
              let value = 5 - ["A", "B", "C", "D", "E"].indexOf(cells[j]);
              data.evaluations.push({
                title: header[j].title,
                value,
              });
              if (data.evaluationMin > value) {
                data.evaluationMin = value;
              }
              data.evaluationScore += value * 10 + 45;
              if (value > 5) {
                this.errors.push(
                  "评定成绩异常：! (row: " +
                    i +
                    ", col: " +
                    (j + 1) +
                    "): " +
                    cells[j] +
                    ", val: " +
                    value +
                    ", title: " +
                    header[j].title
                );
                // console.log('row: ' + (i + 1) + ', col: ' + (j + 1) + ', raw: ' + cells[j] + ', val: ' + value + ', title: ' + header[j].title);
              }
            } else if (header[j].column == "coachComments") {
              data.coachComments = cells[j];
            } else if (
              header[j].column == "traineeComments" &&
              cells[j].length > 2
            ) {
              data.traineeComments = cells[j];
              // console.log('row: ' + (i+1) + ', col: ' +(j+1) + ', raw: ' + cells[j]);
            } else if (header[j].column == "commitTime") {
              // 2022-03-28 14:56:26
              data.commitTime =
                cells[j].substring(0, 10) + " " + cells[j].substring(10, 18);
              // data.commitTime = cells[j];
            }
          }
          data.failedSubjects = [];
          if (
            cells[indexOfailedSubjects] &&
            cells[indexOfailedSubjects].length > 0
          ) {
            data.failedSubjects = cells[indexOfailedSubjects].split(",");
          }
          let del = data.failedSubjects.indexOf("无需加练");
          if (del == -1) {
            del = data.failedSubjects.indexOf("不需要");
          }
          if (del > -1) {
            data.failedSubjects.splice(del, 1);
          }
          data.failedSubjectsCount = data.failedSubjects.length;
          if (data.failedSubjects.length > 0) {
            for (let j = 0; j < data.subjectsComments.length; j++) {
              if (
                data.failedSubjects.includes(data.subjectsComments[j].subject)
              ) {
                data.subjectsComments[j].pass = "否";
                // if (data.pass == "是") {
                //   this.errors.push(data.traineeName + 'passed but failed subject: ' + data.subjectsComments[j].subject + ', row: ' + i);
                //   console.log(data.traineeName + 'passed but failed subject: ' + data.subjectsComments[j].subject);
                // }
              }
            }
          }
          data.evaluationScore = Math.round(data.evaluationScore / 6, 0);
          if (data.subjects.length < 1) {
            console.log("Subjects not found!");
            break;
          }
          if (data.evaluations.length < 6) {
            console.log("Evaluations less than 6!");
            break;
          }
          content.push(data);
        }
        this.content = content;
        this.loading = false;
      } catch (e) {
        console.log(e);
        this.loading = false;
      }
    },
    getUsrNum(userName) {
      for (let i = 0; i < this.userList.length; i++) {
        if (this.userList[i].name == userName) return this.userList[i].number;
      }
      return 0;
    },
    checkSubjects(subject) {
      for (let i = 0; i < this.params.subjects.length; i++) {
        for (let j = 0; j < this.params.subjects[i].children.length; j++) {
          if (this.params.subjects[i].children[j].label == subject) {
            console.log("checkSubjects", subject, this.params.subjects, true);
            return true;
          }
        }
      }
      console.log("checkSubjects", subject, this.params.subjects, false);
      return false;
    },
    doImport() {
      this.loading = true;
      this.$store
        .dispatch("importRecord", this.content)
        .then((data1) => {
          console.log("result", data1.result);
          // this.errors = [];
          // this.content = [];
          // this.$notify.success("已完成！");
          this.$store
            .dispatch("importExercise", this.exerciseData)
            .then((data2) => {
              console.log("result", data2.result);
              this.clearData();
              this.$notify.success("已完成！");
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
              this.$notify.error("An Error Occurred!");
            });
        })
        .catch(() => {
          this.loading = false;
          this.$notify.error("An Error Occurred!");
        });
    },
    clearData() {
      this.raw = "";
      this.content = [];
      this.errors = [];
      this.exerciseData = JSON.parse(this.exerciseDataBackup);
    },
  },
  mounted() {
    this.exerciseDataBackup = JSON.stringify(this.exerciseData);
  },
};
</script>

<style scoped>
.json_wrapper {
  margin: 12px 0;
  padding: 12px;
  width: 100%;
  /* height: 40em; */
  border: 1px solid #dcdfe6;
  height: calc(100vh - 240px);
  background-color: #f2f6fc;
  color: #909399;
  overflow-y: scroll;
  overflow-x: hidden;
}
</style>
